package com.dd.cloud.user.service.pres.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.PresConstants;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.PinYinUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.pres.PresHistory;
import com.dd.cloud.user.mapper.pres.PresHistoryMapper;
import com.dd.cloud.user.req.pres.PresHistoryCreateReq;
import com.dd.cloud.user.req.pres.PresHistoryPageReq;
import com.dd.cloud.user.req.pres.PresHistoryUpdateReq;
import com.dd.cloud.user.res.pres.PresHistoryDetailRes;
import com.dd.cloud.user.res.pres.PresHistoryPageRes;
import com.dd.cloud.user.service.pres.IPresHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class PresHistoryServiceImpl extends ServiceImpl<PresHistoryMapper, PresHistory> implements IPresHistoryService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 修改处方历史草稿
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPresHistory(PresHistoryCreateReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        log.info("req:{}", req);
        String pinyin = PinYinUtils.chineseToPinyinSell(req.getPatientName());
        if (req.getType() == 2) {
            pinyin += "," + PinYinUtils.chineseToPinyinSell(req.getDiagnosis());
        }
        PresHistory ph = new PresHistory();
        BeanUtils.copyProperties(req, ph);
        ph.setPinyin(pinyin);
        ph.setDoctorId(loginInfo.getId());
        ph.setStatus(PresConstants.PresHistoryStatus.NOMER);
        ph.setCreateDate(LocalDateTime.now());
        ph.setUpdateDate(LocalDateTime.now());
        boolean flag = save(ph);
        if (!flag) {
            throw new ZekeException(400, "保存处方历史失败");
        }
    }

    /**
     * 修改处方历史草稿
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePresHistory(PresHistoryUpdateReq req) {
        UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        log.info("req:{}", req);
        String pinyin = PinYinUtils.chineseToPinyinSell(req.getPatientName());
        if (req.getType() == 2) {
            pinyin += "," + PinYinUtils.chineseToPinyinSell(req.getDiagnosis());
        }
        PresHistory ph = new PresHistory();
        BeanUtils.copyProperties(req, ph);
        ph.setPinyin(pinyin);
        ph.setUpdateDate(LocalDateTime.now());
        boolean flag = updateById(ph);
        if (!flag) {
            throw new ZekeException(400, "保存处方历史失败");
        }
        redisTemplate.delete("dd-pres-history-" + ph.getId());
    }

    /**
     * 修改处方历史状态
     *
     * @param id
     * @param status
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePresHistoryStatus(Integer id, Integer status) {
        PresHistory ph = new PresHistory();
        ph.setId(id);
        ph.setStatus(status);
        ph.setUpdateDate(LocalDateTime.now());
        boolean flag = updateById(ph);
        if (!flag) {
            throw new ZekeException(400, "修改处方历史状态失败");
        }
        redisTemplate.delete("dd-pres-history-" + ph.getId());
    }

    /**
     * 查询处方历史草稿列表 分页
     *
     * @param req
     * @return
     */
    @Override
    public IPage<PresHistoryPageRes> queryPresHistoryPage(PresHistoryPageReq req) {
        IPage<PresHistoryPageRes> iPage = req.pagePojo();
        if (req.getKeyword() != null) {
            req.setKeyword(req.getKeyword().toLowerCase());
        }
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        req.setDoctorId(loginInfo.getId());
        iPage = getBaseMapper().queryPresHistoryPage(iPage, req);
        return iPage;
    }

    /**
     * 查询处方历史草稿详情
     *
     * @param id
     * @return
     */
    @Override
    public PresHistoryDetailRes queryPresHistoryDetail(Integer id) {
        PresHistoryDetailRes res;
        String value = redisTemplate.opsForValue().get("dd-pres-history-" + id);
        if (value == null) {
            QueryWrapper<PresHistory> qw = new QueryWrapper<>();
            qw.lambda().eq(PresHistory::getId, id);
            qw.lambda().ne(PresHistory::getStatus, PresConstants.PresHistoryStatus.DEL);
            PresHistory ph = getOne(qw);
            if (ph == null) {
                throw new ZekeException(400, "历史记录查询失败");
            }
            res = new PresHistoryDetailRes();
            BeanUtils.copyProperties(ph, res);
            redisTemplate.opsForValue().set("dd-pres-history-" + ph.getId(), JSON.toJSONString(res), 1L, TimeUnit.HOURS);
            return res;
        } else {
            res = JSON.parseObject(value, PresHistoryDetailRes.class);
        }
        return res;
    }
}
